package com.controller.Front;


import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.common.MD5.AppMD5Util;
import com.common.ajax.AjaxRes;
import com.common.utils.DateUtils;
import com.common.utils.base.UuidUtil;
import com.controller.base.BaseController;
import com.entity.LoginTable;
import com.entity.Users;
import com.service.LoginService;
import com.service.UsersService;

@Controller
@RequestMapping("/frontlogin/") 
public class FrontLoginController extends BaseController<Object>{
	@Autowired
	private LoginService loginService;
	//用户
	@Autowired
	private UsersService useService;
	
	@RequestMapping("/log")
	@ResponseBody
	public AjaxRes log(LoginTable login){
		System.out.println("进入登陆验证方法");
		AjaxRes ajax=new AjaxRes();
		login.setLoginPassword(AppMD5Util.MD5(login.getLoginPassword()));
		int findlog=loginService.count(login);
		if(findlog>0){
			Users user=new Users();
			user.setLoginAccount(login.getLoginAccount());
			List<Users> userList=useService.findByLogin(user);
			HttpSession session=getRequest().getSession();
			if( userList!=null  && !userList.isEmpty() ){
				userList.get(0).setLoginAccount(login.getLoginAccount());
				session.setAttribute("FrontUser", userList.get(0));
			}else{
				Users NullUser=new Users();
				NullUser.setUsersName("游客");
				session.setAttribute("FrontUser",NullUser);
			}
			System.out.println("验证成功存储session：--------------"+session.getAttribute("FrontUser"));
			ajax.setResMsg("登陆成功");
			return ajax;
		}else{
			ajax.setResMsg("账号或密码输入错误");
			return ajax;
		}
	}
	
	/**
	 * 登陆
	 * @return
	 */
	@RequestMapping("/register")
	public ModelAndView register(){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("FrontEnd/register");
		return mv;
	}
	
	
	@RequestMapping("/logout")
	@ResponseBody
	public ModelAndView logout(){
		ModelAndView mv =  new ModelAndView();
		HttpSession session=getRequest().getSession();
		session.setAttribute("login", null);
		mv.setViewName("pages/login" );
		return mv;
	}

	
	@Transactional//事务回滚
	@RequestMapping("/registered")
	@ResponseBody
	public AjaxRes registered(LoginTable login){
		AjaxRes ajax=new AjaxRes();
		try {
			login.setLoginId(UuidUtil.get32UUID());
			login.setLoginPassword(AppMD5Util.MD5(login.getLoginPassword()));
			login.setLastLoginTime(DateUtils.getDate("yyyy/MM/dd HH:mm:ss"));
			System.out.println("加密密码------------------------"+login.getLoginPassword());
			loginService.insert(login);
			ajax.setResMsg("注册成功");
			return ajax;
		} catch (Exception e) {
			ajax.setResMsg("注册失败");
			return ajax;
		}
	}
	
}
